<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
      label-position="left"
    >
      <div class="title-container">
        <h3 class="title">
          <img src="../../assets/login/WMS后台logo.png" />
          <!-- {{ $t('login.title') }} -->
        </h3>
        <lang-select class="set-language" />
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
        class="elInput"
          ref="username"
          v-model="loginForm.username"
          :placeholder="$t('login.username')"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="userPwd">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
          class="elInput"
            :key="passwordType"
            ref="password"
            v-model="loginForm.userPwd"
            :type="passwordType"
            :placeholder="$t('login.password')"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>
      <!-- <el-form-item prop="authorizeDataCode">
          <span class="svg-container">
            <svg-icon icon-class="list" />
          </span>
        <el-select class="elInput" v-model="loginForm.authorizeDataCode" placeholder="请选择仓库" clearable style="width:92%">
          <el-option
            v-for="item in partyGroupList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item> -->
      <el-button
        :loading="loading"
        type="primary"
        style="width:100%;margin-bottom:30px;"
        @click.native.prevent="handleLogin"
      >{{ $t('login.logIn') }}</el-button>
    </el-form>

    <el-dialog :title="$t('login.thirdparty')" :visible.sync="showDialog">
      {{ $t('login.thirdpartyTips') }}
      <br />
      <br />
      <br />
      <social-sign />
    </el-dialog>
    <!-- <div class="footer">
      <img src="../../assets/login/newfooterimg.png" />
    </div> -->
  </div>
</template>

<script>
import Vue from "vue";
import "xe-utils";
import VXETable from "vxe-table";
import "vxe-table/lib/index.css";
import XEUtils from "xe-utils";
import request from '@/utils/loginRequest'
import VXEUtils from "vxe-utils";
Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ["cookie"] });
import LangSelect from "@/components/LangSelect";
import SocialSign from "./components/SocialSignin";
const Base64 = require("js-base64").Base64;

export default {
  name: "Login",
  components: { LangSelect, SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 8) {
        callback(new Error("密码长度最低位8位"));
      } else {
        callback();
      }
    };
    return {
      logindisbled: true,

      loginForm: {
        client_id: this.$store.getters.client_id,
        client_secret: this.$store.getters.client_secret,
        grant_type: "password",
        response_type: "token",
        device_id: "0000000000",
        username: "",
        authorizeDataCode:'',
        userPwd: "",
        password: "",
        time: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername }
        ],
        userPwd: [
          { required: true, trigger: "blur", validator: validatePassword }
        ],
        // authorizeDataCode: [
        //   { required: true, trigger: 'blur', message: '请选择仓库'}
        // ]

      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      partyGroupList:[],
      otherQuery: {}
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true
    },
    'loginForm.authorizeDataCode'(value) {
      if (value) {
        this.logindisbled = false
      } else {
        this.logindisbled = true
      }
    }
  },
  mounted() {
    if (this.$route.query.uid) {
      const _uid = this.$route.query.uid
      if (_uid != '' || typeof _uid != 'undefined') {
        const jmUuid = Base64.decode(_uid)
        const dxUid = this.sortString(decodeURIComponent(jmUuid))
        const jmUid = Base64.decode(dxUid)
        const oneSub = this.getCaption(jmUid, 0)
        this.loginForm.username = this.getCaption(oneSub, 0)
        this.loginForm.userPwd = this.getCaption(jmUid, 1)
        this.logindisbled = false

        this.handleLogin('loginForm')
      }
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {



    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (
          (shiftKey && key >= "a" && key <= "z") ||
          (!shiftKey && key >= "A" && key <= "Z")
        ) {
          this.capsTooltip = true;
        } else {
          this.capsTooltip = false;
        }
      }
      if (key === "CapsLock" && this.capsTooltip === true) {
        this.capsTooltip = false;
      }
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;

          const time = XEUtils.toDateString(new Date(), "yyyyMMddHHmmss");
          const password = Base64.encode(
            this.loginForm.userPwd + "_arpa_" + time
          );
          this.loginForm.time = time;
          this.loginForm.password = password;

          this.$store
            .dispatch("user/login", this.loginForm)
            .then(() => {
              this.$router.push({
                path: this.redirect || "/",
                query: this.otherQuery
              });
              this.logindisbled = false
              this.loading = false;
            })
            .catch(() => {
              this.logindisbled = false
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    //字符截取
    getCaption(obj, state) {
      let index = obj.lastIndexOf('_')
      if (state == 0) {
        obj = obj.substring(0, index)
      } else {
        obj = obj.substring(index + 1, obj.length)
      }
      return obj
    },
    //倒序
    sortString(str) {
      return str
        .split('')
        .reverse('')
        .join('')
    }
  }
};
</script>

<style lang="scss" >
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .elInput input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .elInput {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: #3f4b5a;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  // .verify-bar-area {
  //   width: 450px !important;
  // }
  .verify-btn {
    display: none;
  }
  .verify-move-block {
    border-radius: 5px 0 0 5px;
  }
  .verify-bar-area .verify-left-bar {
    border-radius: 5px;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  //background-color: $bg;
  //overflow: hidden;
  background: url('../../assets/login/loginimg.png');
  background-size: 100% 100%;
  height: 100%;
  position: fixed;
  width: 100%;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 20px auto;
      text-align: center;
      font-weight: bold;
      img {
        width: 80%;
      }
    }

    .set-language {
      color: #fff;
      position: absolute;
      top: 3px;
      font-size: 18px;
      right: 0px;
      cursor: pointer;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: 6px;
  }

  @media only screen and (max-width: 470px) {
    .thirdparty-button {
      display: none;
    }
  }
}
.footer {
  width: 220px;
  margin: 260px auto 0;
  img {
    width: 220px;
  }
}
</style>
